package thread4;

import java.util.Random;

//取款人
public class MoneyTaker extends Thread {
	private Account ac;

	public MoneyTaker(String name, Account ac) {
		super(name);
		this.ac = ac;
	}

	@Override
	public void run() {
		// 不断取钱
		Random r = new Random();

		while (true) {
			int m = r.nextInt(400);
			try {
				super.sleep(30);
			} catch (InterruptedException e1) {
				// TODO 自动生成的 catch 块
				e1.printStackTrace();
			}
			System.out.println(super.getName() + "准备取钱" + m + "元");
			synchronized (ac) {
				while (ac.getBalance() < m) {
					try {
						System.out.println(super.getName() + "准备取钱" + m
								+ "元,余额不足，等着！");
						ac.wait();
						// 等着！
						System.out.println(super.getName() + "准备取钱" + m
								+ "元,被唤醒，继续取钱：");
					} catch (InterruptedException e) {
						// TODO 自动生成的 catch 块
						e.printStackTrace();
					}
				}
				// 被唤醒
				ac.takeMoney(m);
				System.out.println(super.getName() + "准备取钱" + m + "元,取钱成功！"
						+ "现在余额是" + ac.getBalance() + "元");
				// ac.notify();

			}

		}
	}
}
